"""GUI主窗口模块"""
import tkinter as tk
from tkinter import ttk, messagebox

from config.settings import WINDOW_TITLE, WINDOW_SIZE
from utils.screenshot import capture_screenshot_with_selection


class OCRGUI:
    """OCR图形用户界面类"""

    def __init__(self, ocr_engine):
        self.ocr = ocr_engine
        self.root = None
        self.original_text = None
        self.translated_text = None
        self.status_label = None
        self.translate_var = None
        self.language_combo = None
        # 常用语言列表
        self.languages = {
            "中文": "中文",
            "English": "英文",
            "日本語": "日文",
            "Français": "法文",
            "Español": "西班牙文",
            "Русский": "俄文",
            "العربية": "阿拉伯文",
            "Deutsch": "德文"
        }
        # 新增：保存截图用于OCR识别
        self.current_screenshot = None
        self.ocr_button = None  # 新增：OCR识别按钮
        self.translate_button = None

    def create_gui(self):
        """创建图形用户界面"""
        # 创建主窗口
        self.root = tk.Tk()
        self.root.title(WINDOW_TITLE)
        self.root.geometry(WINDOW_SIZE)
        self.root.configure(bg='#f0f0f0')

        # 设置样式
        style = ttk.Style()
        style.theme_use('clam')  # 使用现代化主题

        # 标题
        title_frame = tk.Frame(self.root, bg='#f0f0f0')
        title_frame.pack(fill=tk.X, padx=20, pady=(20, 10))
        title_label = tk.Label(title_frame, text="屏幕OCR识别工具", font=("宋体", 18, "bold"), bg='#f0f0f0',
                               fg='#333')
        title_label.pack()

        # 创建分隔窗体，用于显示原文和译文
        paned_window = tk.PanedWindow(self.root, orient=tk.VERTICAL, sashrelief=tk.RAISED, sashwidth=5, bg='#d0d0d0')
        paned_window.pack(fill=tk.BOTH, expand=1, padx=20, pady=10)

        # 原文区域
        original_frame = tk.Frame(paned_window, bg='#f0f0f0')
        original_frame.pack(fill=tk.BOTH, expand=1)

        original_header = tk.Frame(original_frame, bg='#4a90e2')
        original_header.pack(fill=tk.X)
        tk.Label(original_header, text="原文", font=("宋体", 12, "bold"), bg='#4a90e2', fg='white', padx=10,
                 pady=5).pack(side=tk.LEFT)

        # 创建原文文本框和滚动条的容器
        original_text_frame = tk.Frame(original_frame)
        original_text_frame.pack(fill=tk.BOTH, expand=1, padx=2, pady=2)

        self.original_text = tk.Text(original_text_frame, height=8, width=50, wrap=tk.WORD, font=("微软雅黑", 11),
                                     bg='white', fg='#333', relief=tk.FLAT, borderwidth=1)
        self.original_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        # 添加滚动条到原文文本框
        original_scrollbar = ttk.Scrollbar(original_text_frame, command=self.original_text.yview)
        original_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.original_text.config(yscrollcommand=original_scrollbar.set)

        # 译文区域
        translated_frame = tk.Frame(paned_window, bg='#f0f0f0')
        translated_frame.pack(fill=tk.BOTH, expand=1)

        translated_header = tk.Frame(translated_frame, bg='#7dbcea')
        translated_header.pack(fill=tk.X)
        tk.Label(translated_header, text="译文", font=("宋体", 12, "bold"), bg='#7dbcea', fg='white', padx=10,
                 pady=5).pack(side=tk.LEFT)

        # 创建译文文本框和滚动条的容器
        translated_text_frame = tk.Frame(translated_frame)
        translated_text_frame.pack(fill=tk.BOTH, expand=1, padx=2, pady=2)

        self.translated_text = tk.Text(translated_text_frame, height=8, width=50, wrap=tk.WORD, font=("微软雅黑", 11),
                                       bg='white', fg='#333', relief=tk.FLAT, borderwidth=1)
        self.translated_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        # 添加滚动条到译文文本框
        translated_scrollbar = ttk.Scrollbar(translated_text_frame, command=self.translated_text.yview)
        translated_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.translated_text.config(yscrollcommand=translated_scrollbar.set)

        # 添加到分隔窗体
        paned_window.add(original_frame)
        paned_window.add(translated_frame)

        # 控制按钮区域
        button_frame = tk.Frame(self.root, bg='#f0f0f0')
        button_frame.pack(pady=10)

        # 使用 ttk.Button 创建现代化按钮
        capture_region_btn = ttk.Button(button_frame, text="选择区域截图", command=self.select_region_and_capture,
                                        width=15)
        capture_region_btn.pack(side="left", padx=10)

        # 新增：OCR识别按钮（初始禁用）
        self.ocr_button = ttk.Button(button_frame, text="执行OCR识别", command=self.perform_ocr_from_button,
                                     width=15, state="disabled")
        self.ocr_button.pack(side="left", padx=10)

        # 新增：翻译按钮
        self.translate_button = ttk.Button(button_frame, text="翻译", command=self.translate_text,
                                           width=15)
        self.translate_button.pack(side="left", padx=10)

        # 新增：从剪贴板识别按钮
        clipboard_button = ttk.Button(button_frame, text="识别剪贴板内容", command=self.recognize_from_clipboard,
                                      width=15)
        clipboard_button.pack(side="left", padx=10)

        # 翻译选项区域
        translate_frame = tk.Frame(self.root, bg='#f0f0f0')
        translate_frame.pack(pady=10)

        tk.Label(translate_frame, text="翻译为:", font=("宋体", 10), bg='#f0f0f0').pack(side="left", padx=(0, 10))

        # 创建语言选择下拉框
        self.language_combo = ttk.Combobox(translate_frame, width=12, font=("宋体", 10))
        self.language_combo['values'] = list(self.languages.keys())
        self.language_combo.current(0)  # 默认选择中文
        self.language_combo.pack(side="left", padx=5)

        # 提示信息
        info_frame = tk.Frame(self.root, bg='#f0f0f0')
        info_frame.pack(pady=5)
        tk.Label(info_frame, text="支持中英文识别(通义灵码AI)", font=("宋体", 9), fg="#666", bg='#f0f0f0').pack()

        # 状态栏
        status_frame = tk.Frame(self.root, bg='#f0f0f0')
        status_frame.pack(fill=tk.X, side=tk.BOTTOM, pady=10)
        self.status_label = tk.Label(status_frame, text="就绪", font=("宋体", 9), fg="#666", bg='#f0f0f0')
        self.status_label.pack()

        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)

    def translate_text(self):
        """执行翻译操作"""
        try:
            # 获取原文内容
            original_content = self.original_text.get(1.0, tk.END).strip()
            if not original_content:
                self.status_label.config(text="没有可翻译的文本", fg="#f44336")
                return

            # 获取目标语言
            selected_language = self.language_combo.get()
            target_language = self.languages.get(selected_language, "中文")

            if target_language:
                self.status_label.config(text="正在翻译...", fg="#ff9800")
                self.root.update_idletasks()

                # 执行翻译
                translated_result = self.ocr.translate_text(original_content, target_language)

                # 显示译文
                self.translated_text.delete(1.0, tk.END)
                self.translated_text.insert(tk.END, translated_result)

                self.status_label.config(text="翻译完成", fg="#4caf50")
        except Exception as e:
            self.status_label.config(text="翻译出错", fg="#f44336")
            messagebox.showerror("翻译错误", f"翻译过程中出现错误: {e}")

    def on_translate_option_change(self, *args):
        """翻译选项改变时的处理"""
        pass  # 删除:if self.translate_var.get() == "yes":

    def select_region_and_capture(self):
        """选择区域并截图识别"""
        try:
            self.status_label.config(text="请选择截图区域...", fg="#ff9800")
            self.root.update()

            # 隐藏主窗口
            self.root.withdraw()

            # 使用选择器截图并在原位置显示置顶预览
            screenshot = capture_screenshot_with_selection(show_overlay=True)

            # 显示主窗口
            self.root.deiconify()
            self.root.lift()
            self.root.focus_force()

            if screenshot:
                # 保存截图并启用OCR按钮
                self.current_screenshot = screenshot
                self.ocr_button.config(state="normal")
                self.status_label.config(text="截图完成，请点击'执行OCR识别'按钮", fg="#4caf50")
            else:
                self.status_label.config(text="未选择区域或截图失败", fg="#f44336")
                self.ocr_button.config(state="disabled")
                self.translate_button.config(state="disabled")
        except Exception as e:
            # 确保在出错时也显示主窗口
            self.root.deiconify()
            self.root.lift()
            self.status_label.config(text="识别出错", fg="#f44336")
            messagebox.showerror("错误", f"区域截图识别失败: {e}")

    # 新增：从按钮执行OCR识别
    def perform_ocr_from_button(self):
        """从按钮触发OCR识别"""
        if self.current_screenshot:
            # 禁用OCR按钮防止重复点击
            self.ocr_button.config(state="disabled")

            # 使用线程进行OCR识别，避免阻塞GUI线程
            import threading
            ocr_thread = threading.Thread(
                target=self._perform_ocr_and_update_ui,
                args=(self.current_screenshot,),
                daemon=True)
            ocr_thread.start()
        else:
            self.status_label.config(text="没有可用的截图", fg="#f44336")

    def _perform_ocr_and_update_ui(self, screenshot):
        """
        在后台线程中执行OCR识别并更新UI

        Args:
            screenshot: 截图图像
        """
        try:
            # 在主线程中更新状态
            self.root.after(0, lambda: self.status_label.config(text="正在识别...", fg="#ff9800"))

            # 执行OCR识别（在后台线程中）
            result = self.ocr.recognize_auto(screenshot)

            # 在主线程中更新UI
            self.root.after(0, self._update_ui_after_ocr, result)
        except Exception as e:
            # 在主线程中处理错误
            self.root.after(0, self._handle_ocr_error, e)

    def _update_ui_after_ocr(self, result):
        """
        在主线程中更新UI

        Args:
            result: OCR识别结果
        """
        # 显示原文
        self.original_text.delete(1.0, tk.END)
        self.original_text.insert(tk.END, result)

        # 启用翻译按钮
        self.translate_button.config(state="normal")

        self.status_label.config(text="识别完成", fg="#4caf50")
        print(f"区域截图识别结果: {result}")

        # 清除当前截图
        self.current_screenshot = None

    def _handle_ocr_error(self, error):
        """
        在主线程中处理OCR错误

        Args:
            error: 错误信息
        """
        self.root.deiconify()
        self.root.lift()
        self.status_label.config(text="识别出错", fg="#f44336")
        messagebox.showerror("错误", f"区域截图识别失败: {error}")
        # 重新启用OCR按钮
        self.ocr_button.config(state="normal")

    def recognize_from_clipboard(self):
        """从剪贴板识别内容"""
        try:
            self.status_label.config(text="正在识别剪贴板内容...", fg="#ff9800")
            self.root.update_idletasks()

            # 导入剪贴板相关模块
            from PIL import ImageGrab, Image
            import tkinter as tk

            # 尝试获取剪贴板中的图像
            try:
                # 尝试获取剪贴板图像
                clipboard_image = ImageGrab.grabclipboard()

                if clipboard_image is not None and isinstance(clipboard_image, Image.Image):
                    # 是图像，执行OCR识别
                    import threading
                    ocr_thread = threading.Thread(
                        target=self._perform_ocr_and_update_ui,
                        args=(clipboard_image,),
                        daemon=True)
                    ocr_thread.start()
                    return
                else:
                    # 不是图像，尝试获取文本
                    clipboard_text = self.root.clipboard_get()
                    if clipboard_text and isinstance(clipboard_text, str):
                        # 是文本，直接显示并启用翻译功能
                        self.original_text.delete(1.0, tk.END)
                        self.original_text.insert(tk.END, clipboard_text)
                        self.translate_button.config(state="normal")
                        self.status_label.config(text="已获取剪贴板文本", fg="#4caf50")
                        return
                    else:
                        self.status_label.config(text="剪贴板中没有图像或文本", fg="#f44336")
                        return
            except tk.TclError:
                # 获取剪贴板文本失败
                self.status_label.config(text="剪贴板中没有图像或文本", fg="#f44336")
                return
        except Exception as e:
            self.status_label.config(text="识别出错", fg="#f44336")
            messagebox.showerror("错误", f"识别剪贴板内容失败: {e}")

    def on_closing(self):
        """关闭窗口时的处理"""
        self.root.destroy()

    def run(self):
        """运行GUI"""
        self.create_gui()
        self.root.mainloop()
